<template>
  <div class="create-components-list">
    <div v-for="(component, index) in components" :key="index" class="component"
         @click="handleItemClick(component)">
      <l-text :props="component" />
    </div>
    <StyledUploader @success="onImageUploaded"></StyledUploader>
  </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue'
import LText from './LText.vue'
import StyledUploader from "@/components/StyledUploader.vue";
import {RespUploadData} from "@/types/respTypes.ts";
import {imageDefaultProps} from "@/defaultProps.ts";
import {message} from "ant-design-vue";
import {getImageDimensions} from "@/helper.ts";
import {AllProps, ImageProps, TextProps} from "@/types/props.ts";
import {ComponentData} from "@/types/editor.ts";

export default defineComponent({
  name: "ComponentsList",
  props: {
    components: {
      type: Array<Partial<TextProps>>,
      required: true
    }
  },
  emits: ['on-item-click'],
  components: {
    StyledUploader,
    LText
  },
  setup(props, ctx) {
    const handleItemClick = (componentProps: Partial<AllProps>) => {
      const componentData: Partial<ComponentData> = {
        name: 'l-text',
        props: { ...componentProps },
        isHidden: false,
        isLocked: false,
      }
      ctx.emit('on-item-click', componentData)
    }
    const onImageUploaded = (data: { resp: RespUploadData; file: File }) => {
      const file = data.file
      const componentData: Partial<ComponentData> = {
        name: 'l-image',
        props: { ...imageDefaultProps } as ImageProps,
        isHidden: false,
        isLocked: false,
      }
      message.success('上传成功')
      // componentData.props.src = resp.data.urls[0]
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        if (componentData.props === undefined) {
          return
        }
        componentData.props.src = reader.result as string;
        getImageDimensions(componentData.props.src).then(({ width }) => {
          const maxWidth = 373
          if (componentData.props === undefined) {
            return
          }
          componentData.props.width = ((width > maxWidth) ? maxWidth : width) + 'px'
          ctx.emit('on-item-click', componentData)
        })
      };
    }
    return {
      handleItemClick,
      onImageUploaded
    }
  }
})
</script>

<style scoped>
.component {
  margin-bottom: 10px;
}
.component > * {
  position: static !important;
}
</style>